package com.nx.platform.es.system.config;

import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.nx.platform.es.common.utils.YamlParser;
import com.nx.platform.es.bean.dto.ESQueryConfDTO;
import com.nx.platform.es.common.utils.Constants;
import com.nx.platform.es.common.utils.MoreMaps;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * ES配置管理实现
 * 搜索条件管理
 * <p>
 * Created by  on 2017/4/14.
 */

@Component
public class ESQueryConfigure {

    public ESQueryConfDTO getESEntryConfig(String entry) {
        Map<String, ESQueryConfDTO> entryConfigMap = getEntryConfigMap();
        if (entry == null || entryConfigMap == null) {
            return null;
        } else {
            return entryConfigMap.get(entry);
        }
    }

    protected void startUp() throws Exception {
        Preconditions.checkState(getEntryConfigMap() != null);
    }

    protected void shutDown() throws Exception {}

    @SuppressWarnings("unchecked")
    private Map<String, ESQueryConfDTO> getEntryConfigMap() {
        return (Map<String, ESQueryConfDTO>) ConfigCenter.getConfig(Constants.ES_CONFIG, this::parse).orElse(null);
    }

    private Map<String, ESQueryConfDTO> parse(@NotNull String newValue) throws Exception {
        final String entryPrefix = "entry.";
        Map<?, ?> settings = YamlParser.parseToMap(newValue);
        Map<String, ESQueryConfDTO> configMap = Maps.newConcurrentMap();
        for (Object entryObj : settings.keySet()) {
            String entryStr = String.valueOf(entryObj);
            if (entryStr.startsWith(entryPrefix)) {
                String entry = entryStr.substring(entryPrefix.length());
                Map<?, ?> entrySetting = MoreMaps.getObject(settings, entryObj);
                configMap.put(entry, ESQueryConfDTO.create(entrySetting));
            }
        }
        if (configMap.isEmpty()) {
            throw new IllegalStateException("config is empty");
        }
        return configMap;
    }

}
